#!/bin/bash
set -e
## 读取配置文件
. ../config/my-config.sh

echo '查看hbase集群信息'
if [ -f 'hbase.info'  ];then
	chmod a+x hbase.info
	cat hbase.info
else
	touch hbase.info
fi

read -p "是否继续(Y/N)？：" isY
if [ "${isY}" != "y" ] && [ "${isY}" != "Y" ];then
   exit 1
fi

## 生成集群配置文件
rm -f regionservers
touch regionservers

cat > hbase-site.xml <<END
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
  <property>
    <name>hbase.rootdir</name>
    <value>hdfs://${HADOOP_MASTER}:9000/hbase</value>
  </property>
  <property>
     <name>hbase.cluster.distributed</name>
     <value>true</value>
  </property>
  <property>
     <name>hbase.master.port</name>
     <value>6000</value>
  </property>
   <property>
    <name>hbase.zookeeper.property.dataDir</name>
    <value>${ZOO_DATA}</value>
  </property>
  <property>
    <name>hbase.zookeeper.quorum</name>
    <value>\${HBASE_ZOOKEEPER_QUORUM}</value>
  </property>
  <property>
    <name>hbase.zookeeper.property.clientPort</name>
    <value>2181</value>
  </property>
</configuration>
END

## 生成临时脚本文件
rm -f tmp.sh
echo "set -e" > tmp.sh

echo "循环写入文件"
i=0
numRow=`cat hbase.info | wc -l`
numMod=$((numRow%2))
HBASE_ZOOKEEPER_QUORUM=""
while read line
do 
    eval $(echo $line | awk '{print "i1="$1";i2="$2";i3="$3}')
    # 追加写入 regionservers
	if [ "$i1" != "name" ];then
		echo "$i2" >> regionservers
	fi
	i=$((i+1))
	# 保证zk集群数为单数
	if [ $i -lt $numRow ] || [ $numMod -ne 0 ]; then
		HBASE_ZOOKEEPER_QUORUM=${HBASE_ZOOKEEPER_QUORUM},${i2}
	fi
	
	## 写入临时脚本
	echo "ssh root@$i3 'mkdir -p $HBASE_HOME;chown -R hadoop:hadoop $HBASE_HOME'" >> tmp.sh
	echo "ssh root@$i3 'mkdir -p $HBASE_DATA;chown -R hadoop:hadoop $HBASE_DATA'" >> tmp.sh
	echo "ssh root@$i3 'mkdir -p $HBASE_LOGS;chown -R hadoop:hadoop $HBASE_LOGS'" >> tmp.sh
done < hbase.info

echo $HBASE_ZOOKEEPER_QUORUM
HBASE_ZOOKEEPER_QUORUM=${HBASE_ZOOKEEPER_QUORUM#*,}
sed -i "s@\${HBASE_ZOOKEEPER_QUORUM}@${HBASE_ZOOKEEPER_QUORUM}@g" hbase-site.xml

echo "分发文件到各个节点"
while read line
do 
    eval $(echo $line | awk '{print "i1="$1";i2="$2";i3="$3}')
    echo "$i2"
    scp regionservers root@${i3}:$HBASE_HOME/conf
    scp hbase-site.xml root@${i3}:$HBASE_HOME/conf
done < hbase.info

echo "执行临时脚本"
chmod a+x tmp.sh;./tmp.sh
